package com.devunion.salon.core.security;

import org.springframework.security.providers.AuthenticationProvider;
import org.springframework.security.providers.UsernamePasswordAuthenticationToken;
import org.springframework.security.*;
import com.devunion.salon.core.dao.UserDao;
import com.devunion.salon.core.model.security.User;

/**
 * @author spetrakovsky
 */
public class SalonAuthenticationProvider implements AuthenticationProvider {

    private UserDao userDao;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // todo check username and passwordd and return authority with right permission

        if (authentication.getCredentials() != null && authentication.getPrincipal() != null) {
            User user = userDao.login((String) authentication.getPrincipal(), (String) authentication.getCredentials());
            if (user != null) {
                GrantedAuthority authority = new GrantedAuthorityImpl("ROLE_USER");
                return new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), "you can't get password, it's protected by security reason"
                        , new GrantedAuthority[]{authority});
            }
        }
        throw new BadCredentialsException("Bad credentials");
    }

    public boolean supports(Class aClass) {
        return UsernamePasswordAuthenticationToken.class == aClass;
    }

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }
}
